<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>02 Ajax方法的封装</title>
</head>
<body>

</body>
</html>


<script>
    //data = {url    method  asyn   success  faild  data}
    function HJax(data) {
        console.log(data)
        // 创建xhr对象
        var xhr = null;
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        var method = null;
        if (data.method == 'GET') {
            method = data.method;
            if (data.data) {
                data.url = data.url + '?' + data.data;
            }
        } else if (data.method == 'POST') {
            method = data.method;
        }
        // 准备发送前的一些配置参数
        xhr.open(data.method, data.url, data.async);

        if (method == 'GET') {
            xhr.send(null);
        } else {
            xhr.send(data.data ? data.data : null);
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    data.success(xhr.responseText);
                } else {
                    data.faild(xhr.responseText);
                }
            }
        }
    }


    HJax({
        url: 'http://www.baidu.com',
        method: 'GET',
        async: true,
        success: function (res) {
            console.log(res);
        },
        faild: function (res) {
            console.log(res);
        }
    });
</script>